<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Redis 在Python中的使用介绍">
<meta name="keywords" content="Redis">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis For Python">
<meta property="og:url" content="https://rencheng.cc/2018/09/02/redis/inPython/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="Redis 在Python中的使用介绍">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://object.renchengqi.com/blog/o2xzb.png">
<meta property="og:updated_time" content="2018-09-02T08:22:49.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Redis For Python">
<meta name="twitter:description" content="Redis 在Python中的使用介绍">
<meta name="twitter:image" content="https://object.renchengqi.com/blog/o2xzb.png">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2018/09/02/redis/inPython/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Redis For Python | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2018/09/02/redis/inPython/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Redis For Python

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-09-02 16:22:49" itemprop="dateCreated datePublished" datetime="2018-09-02T16:22:49+08:00">2018-09-02</time>
            

            
          </span>

          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">11k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Redis 在Python中的使用介绍</p>
<a id="more"></a>
<h1 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h1><h2 id="Ubuntu"><a href="#Ubuntu" class="headerlink" title="Ubuntu"></a>Ubuntu</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 安装</span></span><br><span class="line">sudo apt-get install redis-server</span><br><span class="line"><span class="comment"># 确认是否启动</span></span><br><span class="line">ps -aux | grep redis</span><br><span class="line"><span class="comment"># 服务端启动</span></span><br><span class="line">sudo /etc/init.d/redis-server status</span><br><span class="line">sudo /etc/init.d/redis-server start</span><br><span class="line">sudo /etc/init.d/redis-server stop</span><br><span class="line">sudo /etc/init.d/redis-server restart</span><br><span class="line"><span class="comment"># 客户端连接</span></span><br><span class="line">redis-cli -h IP地址 -p 端口</span><br><span class="line">redis-cli <span class="comment"># 默认连接本机的6379端口</span></span><br><span class="line">127.0.0.1:6379&gt;ping</span><br><span class="line">PONG</span><br></pre></td></tr></table></figure>
<h2 id="Windows"><a href="#Windows" class="headerlink" title="Windows"></a>Windows</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、下载安装包</span><br><span class="line">   https://github.com/ServiceStack/redis-windows/blob/master/downloads/redis<span class="number">-64.3</span><span class="number">.0</span><span class="number">.503</span>.zip</span><br><span class="line"><span class="number">2</span>、解压</span><br><span class="line"><span class="number">3</span>、启动服务端</span><br><span class="line">   双击解压后的 redis-server.exe </span><br><span class="line"><span class="number">4</span>、客户端连接</span><br><span class="line">   双击解压后的 redis-cli.exe</span><br></pre></td></tr></table></figure>
<p><strong>问题：关闭终端后服务终止</strong><br><strong>解决：将Redis服务安装到本地服务</strong><br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、重命名 redis<span class="selector-class">.windows</span><span class="selector-class">.conf</span> 为 redis<span class="selector-class">.conf</span>,作为redis服务的配置文件</span><br><span class="line"><span class="number">2</span>、cmd命令行，进入到redis-server.exe所在目录</span><br><span class="line"><span class="number">3</span>、执行：redis-server --service-install redis<span class="selector-class">.conf</span> --loglevel verbose</span><br><span class="line"><span class="number">4</span>、计算机-管理-服务-Redis-启动</span><br></pre></td></tr></table></figure></p>
<p><strong>卸载</strong><br><figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">到 redis-<span class="keyword">server</span>.exe 所在路径执行：</span><br><span class="line"><span class="number">1</span>、redis-<span class="keyword">server</span> --service-uninstall</span><br><span class="line"><span class="number">2</span>、sc delete Redis</span><br></pre></td></tr></table></figure></p>
<h1 id="配置文件详解"><a href="#配置文件详解" class="headerlink" title="配置文件详解"></a>配置文件详解</h1><h2 id="配置文件所在路径"><a href="#配置文件所在路径" class="headerlink" title="配置文件所在路径"></a>配置文件所在路径</h2><h3 id="Ubuntu-1"><a href="#Ubuntu-1" class="headerlink" title="Ubuntu"></a>Ubuntu</h3><figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="regexp">/etc/</span>redis<span class="regexp">/redis.conf</span></span><br></pre></td></tr></table></figure>
<h3 id="windows"><a href="#windows" class="headerlink" title="windows"></a>windows</h3><p>下载解压后的redis文件夹中<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">redis</span><span class="selector-class">.windows</span><span class="selector-class">.conf</span> </span><br><span class="line"><span class="selector-tag">redis</span><span class="selector-class">.conf</span></span><br></pre></td></tr></table></figure></p>
<h2 id="设置连接密码"><a href="#设置连接密码" class="headerlink" title="设置连接密码"></a>设置连接密码</h2><ol>
<li>requirepass 密码</li>
<li><p>重启服务</p>
 <figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo <span class="regexp">/etc/i</span>nit.d<span class="regexp">/redis-server restart</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li>客户端连接 <figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">redis-cli</span> <span class="selector-tag">-h</span> 127<span class="selector-class">.0</span><span class="selector-class">.0</span><span class="selector-class">.1</span> <span class="selector-tag">-p</span> 6379 <span class="selector-tag">-a</span> 123456</span><br><span class="line">127<span class="selector-class">.0</span><span class="selector-class">.0</span><span class="selector-class">.1</span><span class="selector-pseudo">:6379</span>&gt;<span class="selector-tag">ping</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="允许远程连接"><a href="#允许远程连接" class="headerlink" title="允许远程连接"></a>允许远程连接</h2><ol>
<li><p>注释掉IP地址绑定</p>
 <figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">bind</span> 127<span class="selector-class">.0</span><span class="selector-class">.0</span><span class="selector-class">.1</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>关闭保护模式（默认开始，不允许外部网络访问）</p>
 <figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">protected-mode</span> <span class="literal">no</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>重启redis服务</p>
 <figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo <span class="regexp">/etc/i</span>nit.d<span class="regexp">/redis-server restart</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="远程连接测试"><a href="#远程连接测试" class="headerlink" title="远程连接测试"></a>远程连接测试</h2><h3 id="Windows连接Ubuntu的Redis服务"><a href="#Windows连接Ubuntu的Redis服务" class="headerlink" title="Windows连接Ubuntu的Redis服务**"></a>Windows连接Ubuntu的Redis服务**</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># cmd命令行</span></span><br><span class="line"><span class="number">1</span>、d:</span><br><span class="line"><span class="number">2</span>、cd Redis3<span class="number">.0</span></span><br><span class="line"><span class="number">3</span>、redis-cli -h x.x.x.x -a <span class="number">123456</span></span><br><span class="line"><span class="number">4</span>、x.x.x.x:<span class="number">6379</span>&gt;ping</span><br></pre></td></tr></table></figure>
<h1 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h1><h2 id="字符串类型-string"><a href="#字符串类型-string" class="headerlink" title="字符串类型(string)"></a>字符串类型(string)</h2><h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">字符串、数字，都会转为字符串来存储</span><br><span class="line">以二进制的方式存储在内存中</span><br></pre></td></tr></table></figure>
<h3 id="必须掌握命令"><a href="#必须掌握命令" class="headerlink" title="必须掌握命令"></a>必须掌握命令</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">set key value</span><br><span class="line">setnx key value</span><br><span class="line">set key value ex seconds</span><br><span class="line">get key</span><br><span class="line">mset key1 value1 key2 value2 </span><br><span class="line">mget key1 key2 key3 </span><br><span class="line">stren key </span><br><span class="line"><span class="comment"># 数字操作</span></span><br><span class="line">incr key</span><br><span class="line">decr key</span><br></pre></td></tr></table></figure>
<h3 id="扩展命令"><a href="#扩展命令" class="headerlink" title="扩展命令"></a>扩展命令</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">append key value</span><br><span class="line">setrange key index value</span><br><span class="line">getrange key start stop</span><br><span class="line">incrby key step</span><br><span class="line">decrby key step</span><br></pre></td></tr></table></figure>
<h3 id="常用命令"><a href="#常用命令" class="headerlink" title="常用命令"></a>常用命令</h3><h4 id="set-get命令"><a href="#set-get命令" class="headerlink" title="set | get命令"></a>set | get命令</h4><p><strong>作用</strong>:<br>设置键值，获取键对应的值</p>
<p><strong>命令格式</strong>:<br>set key value<br>get key</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">tarena@tedu:~$ redis-cli -h <span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span> -p <span class="number">6379</span> -a <span class="number">123456</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set name <span class="string">'Lucy'</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get name</span><br><span class="line"><span class="string">"Lucy"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set number <span class="number">10</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"10"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set number <span class="number">6.66</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"6.66"</span></span><br></pre></td></tr></table></figure>
<h4 id="set命令之-setnx"><a href="#set命令之-setnx" class="headerlink" title="set命令之 - setnx"></a>set命令之 - setnx</h4><p>setnx key value : 键不存在时才能进行设置<strong>（必须掌握）</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 键不存在，进行设置（此处name键已经存在）</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; setnx name <span class="string">'Tom'</span></span><br><span class="line">(nil)</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="set命令之-ex"><a href="#set命令之-ex" class="headerlink" title="set命令之 - ex"></a>set命令之 - ex</h4><p><strong>作用:</strong><br>设置过期时间</p>
<p><strong>命令格式:</strong><br>set key value ex seconds</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set name <span class="string">'Tiechui'</span> ex <span class="number">3</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get name</span><br><span class="line"><span class="string">"Tiechui"</span></span><br><span class="line"><span class="comment"># 3秒后再次获取，得到 nil</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get name</span><br><span class="line">(nil)</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="mset-mget"><a href="#mset-mget" class="headerlink" title="mset | mget"></a>mset | mget</h4><p><strong>作用:</strong><br>同时设置多个值，获取多个值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; mset name1 <span class="string">'lucy'</span> name2 <span class="string">'tom'</span> name3 <span class="string">'jim'</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; mget name1 name2 name3</span><br><span class="line"><span class="number">1</span>) <span class="string">"lucy"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"tom"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"jim"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<p><strong>键的命名规范</strong></p>
<p>​mset  wang::email  <em>*</em>@qq.com</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; mset wang::email wangweichao@tedu.cn guo::email guods@tedu.cn</span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; mget wang::email guo::email</span><br><span class="line"><span class="number">1</span>) <span class="string">"wangweichao@tedu.cn"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"guods@tedu.cn"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="strlen"><a href="#strlen" class="headerlink" title="strlen"></a>strlen</h4><p><strong>作用:</strong><br>获取值的长度</p>
<p><strong>命令格式:</strong><br>strlen key</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; strlen name</span><br><span class="line">(integer) <span class="number">11</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="字符串索引操作"><a href="#字符串索引操作" class="headerlink" title="字符串索引操作"></a>字符串索引操作</h4><p><strong>setrange</strong><br>key 索引值 value</p>
<p><strong>作用:</strong><br>从索引值开始，value替换原内容</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get message</span><br><span class="line"><span class="string">"hello world"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; setrange message <span class="number">6</span> <span class="string">'tarena'</span></span><br><span class="line">(integer) <span class="number">12</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get message</span><br><span class="line"><span class="string">"hello tarena"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="getrange-key-起始值-终止值"><a href="#getrange-key-起始值-终止值" class="headerlink" title="getrange key 起始值 终止值"></a>getrange key 起始值 终止值</h4><p><strong>作用:</strong><br>获取指定范围切片内容</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get message</span><br><span class="line"><span class="string">"hello tarena"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; getrange message <span class="number">0</span> <span class="number">4</span></span><br><span class="line"><span class="string">"hello"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; getrange message <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="string">"hello tarena"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="append-key-value"><a href="#append-key-value" class="headerlink" title="append key value"></a>append key value</h4><p><strong>作用:</strong><br>追加拼接value的值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set message <span class="string">'hello '</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; append message <span class="string">'world'</span></span><br><span class="line">(integer) <span class="number">11</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get message</span><br><span class="line"><span class="string">"hello world"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h2 id="整数操作"><a href="#整数操作" class="headerlink" title="整数操作"></a>整数操作</h2><p>INCRBY key 步长</p>
<p>DECRBY key 步长</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set number <span class="number">10</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"10"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; INCRBY number <span class="number">5</span></span><br><span class="line">(integer) <span class="number">15</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"15"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; DECRBY number <span class="number">5</span></span><br><span class="line">(integer) <span class="number">5</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"5"</span></span><br></pre></td></tr></table></figure>
<p><strong>INCR key : +1操作</strong></p>
<p><strong>DECR key : -1操作</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; incr number</span><br><span class="line">(integer) <span class="number">7</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; decr number</span><br><span class="line">(integer) <span class="number">6</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"6"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h3 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h3><p>抖音上有人关注你了，是不是可以用INCR呢，如果取消关注了是不是可以用DECR</p>
<h2 id="浮点数操作"><a href="#浮点数操作" class="headerlink" title="浮点数操作"></a>浮点数操作</h2><p>incrbyfloat key step</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get number</span><br><span class="line"><span class="string">"10"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; INCRBYFLOAT number <span class="number">6.66</span></span><br><span class="line"><span class="string">"12.66"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; INCRBYFLOAT number <span class="number">-6.66</span></span><br><span class="line"><span class="string">"6"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; </span><br><span class="line"><span class="comment"># 先转为数字类型，然后再进行相加减，不能使用append</span></span><br></pre></td></tr></table></figure>
<h2 id="命令汇总"><a href="#命令汇总" class="headerlink" title="命令汇总"></a>命令汇总</h2><h3 id="字符串操作"><a href="#字符串操作" class="headerlink" title="字符串操作"></a>字符串操作</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、set key value</span><br><span class="line"><span class="number">2</span>、setnx key value</span><br><span class="line"><span class="number">3</span>、get key</span><br><span class="line"><span class="number">3</span>、mset</span><br><span class="line"><span class="number">4</span>、mget</span><br><span class="line"><span class="number">5</span>、set key value ex seconds</span><br><span class="line"><span class="number">6</span>、strlen key</span><br></pre></td></tr></table></figure>
<h3 id="数字操作"><a href="#数字操作" class="headerlink" title="数字操作"></a>数字操作</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">7</span>、incrby key 步长</span><br><span class="line"><span class="number">8</span>、decrby key 步长</span><br><span class="line"><span class="number">9</span>、incr key</span><br><span class="line"><span class="number">10</span>、decr key</span><br><span class="line"><span class="number">11</span>、incrbyfloat key number</span><br></pre></td></tr></table></figure>
<h3 id="设置过期时间的两种方式"><a href="#设置过期时间的两种方式" class="headerlink" title="设置过期时间的两种方式"></a>设置过期时间的两种方式</h3><h4 id="方式一"><a href="#方式一" class="headerlink" title="方式一"></a>方式一</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、set key value ex <span class="number">3</span></span><br></pre></td></tr></table></figure>
<h4 id="方式二"><a href="#方式二" class="headerlink" title="方式二"></a>方式二</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、set key value</span><br><span class="line"><span class="number">2</span>、expire key <span class="number">5</span> <span class="comment"># 秒</span></span><br><span class="line"><span class="number">3</span>、pexpire key <span class="number">5</span> <span class="comment"># 毫秒</span></span><br></pre></td></tr></table></figure>
<h3 id="查看存活时间"><a href="#查看存活时间" class="headerlink" title="查看存活时间"></a>查看存活时间</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ttl key</span><br></pre></td></tr></table></figure>
<h3 id="删除过期"><a href="#删除过期" class="headerlink" title="删除过期"></a>删除过期</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">persist key</span><br></pre></td></tr></table></figure>
<h2 id="通用命令"><a href="#通用命令" class="headerlink" title="通用命令"></a>通用命令</h2><ol>
<li><p>切换库</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select number</span><br></pre></td></tr></table></figure>
</li>
<li><p>查看键</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">keys *</span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li><p>键类型</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">TYPE key</span><br></pre></td></tr></table></figure>
</li>
<li><p>键是否存在</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">exists key</span><br></pre></td></tr></table></figure>
</li>
<li><p>删除键</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">del</span> key</span><br></pre></td></tr></table></figure>
</li>
<li><p>键重命名</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rename key newkey</span><br></pre></td></tr></table></figure>
</li>
<li><p>返回旧值并设置新值（如果键不存在，就创建并赋值）</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">getset key value</span><br></pre></td></tr></table></figure>
</li>
<li><p>清除当前库中所有数据（慎用）</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">flushdb</span><br></pre></td></tr></table></figure>
</li>
<li><p>清除所有库中所有数据（慎用）</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">flushall</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><strong>string数据类型注意</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># key值取值原则</span></span><br><span class="line"><span class="number">1</span>、key值不宜过长，消耗内存，且在数据中查找这类键值的计算成本高</span><br><span class="line"><span class="number">2</span>、不宜过短，可读性较差</span><br><span class="line"><span class="comment"># 值</span></span><br><span class="line"><span class="number">1</span>、一个字符串类型的值最多能存储<span class="number">512</span>M内容</span><br></pre></td></tr></table></figure>
<h3 id="列表数据类型（List）"><a href="#列表数据类型（List）" class="headerlink" title="列表数据类型（List）"></a>列表数据类型（List）</h3><h4 id="特点-1"><a href="#特点-1" class="headerlink" title="特点"></a>特点</h4><p>元素是字符串类型<br>列表头尾增删快，中间增删慢，增删元素是常态<br>元素可重复<br>最多可包$2^{32} -1$个元素<br>索引同python列表</p>
<h4 id="头尾压入元素（LPUSH-RPUSH）"><a href="#头尾压入元素（LPUSH-RPUSH）" class="headerlink" title="头尾压入元素（LPUSH | RPUSH）"></a>头尾压入元素（LPUSH | RPUSH）</h4><p>​1、LPUSH key value</p>
<p>​2、RPUSH key value</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LPUSH mylist1 <span class="number">0</span> <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span></span><br><span class="line">(integer) <span class="number">5</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"4"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; RPUSH mylist2 <span class="number">0</span> <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span></span><br><span class="line">(integer) <span class="number">5</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist2 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"4"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="查看-设置-列表元素"><a href="#查看-设置-列表元素" class="headerlink" title="查看|设置 列表元素"></a>查看|设置 列表元素</h4><p>  查看（LRANGE)</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">LRANGE key start stop</span><br><span class="line"><span class="comment"># 查看列表中所有元素</span></span><br><span class="line">LRANGE key <span class="number">0</span> <span class="number">-1</span></span><br></pre></td></tr></table></figure>
<p>  获取指定位置元素（LINDEX）</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LINDEX key index</span><br></pre></td></tr></table></figure>
<p>  设置指定位置元素的值（LSET）</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LSET key index value</span><br></pre></td></tr></table></figure>
<p>  获取列表长度（LLEN)</p>
  <figure class="highlight ebnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">LLEN key</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p><strong>头尾弹出元素（LPOP |  RPOP）</strong></p>
<p>LPOP key : 从列表头部弹出一个元素</p>
<p>RPOP key : 从列表尾部弹出一个元素</p>
<p>RPOPLPUSH source destination : 从一个列表尾部弹出元素压入到另一个列表头部</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"4"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"8"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LPOP mylist1</span><br><span class="line"><span class="string">"4"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; RPOP mylist1</span><br><span class="line"><span class="string">"8"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; RPOPLPUSH mylist1 mylist2</span><br><span class="line"><span class="string">"1"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist2 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"2"</span></span><br></pre></td></tr></table></figure>
<h4 id="移除指定元素（LREM）"><a href="#移除指定元素（LREM）" class="headerlink" title="移除指定元素（LREM）"></a>移除指定元素（LREM）</h4><p>  LREM key count value</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">count&gt;<span class="number">0</span>：表示从头部开始向表尾搜索，移除与value相等的元素，数量为count</span><br><span class="line">count&lt;<span class="number">0</span>：表示从尾部开始向表头搜索，移除与value相等的元素，数量为count</span><br><span class="line">count=<span class="number">0</span>：移除表中所有与value相等的值</span><br></pre></td></tr></table></figure>
<p>  示例</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LPUSH mylist1 <span class="number">3</span> <span class="number">2</span></span><br><span class="line">(integer) <span class="number">4</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LREM mylist1 <span class="number">1</span> <span class="number">2</span></span><br><span class="line">(integer) <span class="number">1</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LREM mylist1 <span class="number">1</span> <span class="number">3</span></span><br><span class="line">(integer) <span class="number">1</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist1 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="去除指定范围外元素（LTRIM）"><a href="#去除指定范围外元素（LTRIM）" class="headerlink" title="去除指定范围外元素（LTRIM）"></a>去除指定范围外元素（LTRIM）</h4><p>  LTRIM key start stop</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist2 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">6</span>) <span class="string">"4"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LTRIM mylist2 <span class="number">0</span> <span class="number">-2</span></span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist2 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<p>  应用场景: 保存微博评论最后500条</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LTRIM user001::comments <span class="number">0</span> <span class="number">499</span></span><br></pre></td></tr></table></figure>
<h4 id="列表中插入值（LINSERT）"><a href="#列表中插入值（LINSERT）" class="headerlink" title="列表中插入值（LINSERT）"></a>列表中插入值（LINSERT）</h4><p>  LINSERT key BEFORE|AFTER pivot value</p>
<p>  key和pivot不存在，不进行任何操作</p>
<p>  示例代码</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist2 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"4"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LINSERT mylist2 after <span class="number">2</span> <span class="number">666</span></span><br><span class="line">(integer) <span class="number">6</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LINSERT mylist2 before <span class="number">4</span> <span class="number">888</span></span><br><span class="line">(integer) <span class="number">7</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; LRANGE mylist2 <span class="number">0</span> <span class="number">-1</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"0"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">3</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">4</span>) <span class="string">"666"</span></span><br><span class="line"><span class="number">5</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">6</span>) <span class="string">"888"</span></span><br><span class="line"><span class="number">7</span>) <span class="string">"4"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="阻塞弹出（BLPOP-BRPOP）"><a href="#阻塞弹出（BLPOP-BRPOP）" class="headerlink" title="阻塞弹出（BLPOP | BRPOP）"></a>阻塞弹出（BLPOP | BRPOP）</h4><p>  BLPOP key timeout</p>
<p>  BRPOP key timeout</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、如果弹出的列表不存在或者为空，就会阻塞</span><br><span class="line"><span class="number">2</span>、超时时间设置为<span class="number">0</span>，就是永久阻塞，直到有数据可以弹出</span><br><span class="line"><span class="number">3</span>、如果多个客户端阻塞再同一个列表上，使用First In First Service原则，先到先服务</span><br></pre></td></tr></table></figure>
<p>  示例</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; BLPOP mylist2 <span class="number">0</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"mylist2"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"3"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; BLPOP mylist2 <span class="number">0</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"mylist2"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"2"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; BLPOP mylist2 <span class="number">0</span></span><br><span class="line"><span class="number">1</span>) <span class="string">"mylist2"</span></span><br><span class="line"><span class="number">2</span>) <span class="string">"1"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; BLPOP mylist2 <span class="number">0</span></span><br><span class="line"><span class="comment"># 阻塞了</span></span><br></pre></td></tr></table></figure>
<p><strong>列表常用命令总结</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 增</span></span><br><span class="line">LPUSH key value1 value2 </span><br><span class="line">RPUSH key value1 value2</span><br><span class="line">RPOPLPUSH source destination</span><br><span class="line">LINSERT key after|before value newvalue</span><br><span class="line"><span class="comment"># 查</span></span><br><span class="line">LRANGE key start stop</span><br><span class="line">LLEN key</span><br><span class="line"><span class="comment"># 删</span></span><br><span class="line">LPOP key</span><br><span class="line">RPOP key</span><br><span class="line">BLPOP key timeout</span><br><span class="line">BRPOP key timeout</span><br><span class="line">LREM key count value</span><br><span class="line">LTRIM key start stop</span><br><span class="line"><span class="comment"># 改</span></span><br><span class="line">LSET key index newvalue</span><br></pre></td></tr></table></figure>
<h1 id="与python交互"><a href="#与python交互" class="headerlink" title="与python交互"></a>与python交互</h1><ul>
<li>模块</li>
</ul>
<p>Ubuntu</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo pip3 install redis</span><br></pre></td></tr></table></figure>
<p>Windows</p>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python -m pip <span class="keyword">install</span> redis</span><br></pre></td></tr></table></figure>
<ul>
<li>使用流程</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"><span class="comment"># 创建数据库连接对象</span></span><br><span class="line">r = redis.Redis(host=<span class="string">'127.0.0.1'</span>,port=<span class="number">6379</span>,db=<span class="number">0</span>,password=<span class="string">'123456'</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li>通用命令代码示例</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建数据库连接对象</span></span><br><span class="line">r = redis.Redis(host=<span class="string">'192.168.43.49'</span>,port=<span class="number">6379</span>,db=<span class="number">0</span>,password=<span class="string">'123456'</span>)</span><br><span class="line"><span class="comment"># [b'key1',b'key2']</span></span><br><span class="line">print(r.keys(<span class="string">'*'</span>))</span><br><span class="line"><span class="comment"># 键类型：string</span></span><br><span class="line">print(type(<span class="string">'spider::urls'</span>))</span><br><span class="line"><span class="comment"># 是否存在：1 或者 0</span></span><br><span class="line">print(r.exists(<span class="string">'spider::urls'</span>))</span><br><span class="line"><span class="comment"># 删除key：spider::urls</span></span><br><span class="line">r.delete(<span class="string">'spider::urls'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>字符串命令代码示例</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"></span><br><span class="line">r = redis.Redis(host=<span class="string">'192.168.43.49'</span>,port=<span class="number">6379</span>,db=<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line">r.set(<span class="string">'mystring'</span>,<span class="string">'python'</span>)</span><br><span class="line"><span class="comment"># b'python'</span></span><br><span class="line">print(r.get(<span class="string">'mystring'</span>))</span><br><span class="line"><span class="comment"># False</span></span><br><span class="line">print(r.setnx(<span class="string">'mystring'</span>,<span class="string">'socket'</span>))</span><br><span class="line"><span class="comment"># mset：参数为字典</span></span><br><span class="line">r.mset(&#123;<span class="string">'mystring2'</span>:<span class="string">'mysql'</span>,<span class="string">'mystring3'</span>:<span class="string">'mongodb'</span>&#125;)</span><br><span class="line"><span class="comment"># mget：结果为一个列表</span></span><br><span class="line">print(r.mget(<span class="string">'mystring'</span>,<span class="string">'mystring2'</span>,<span class="string">'mystring3'</span>))</span><br><span class="line"><span class="comment"># mystring长度：6</span></span><br><span class="line">print(r.strlen(<span class="string">'mystring'</span>))</span><br><span class="line"><span class="comment"># 数字类型操作</span></span><br><span class="line">r.set(<span class="string">'number'</span>,<span class="number">10</span>)</span><br><span class="line">r.incrby(<span class="string">'number'</span>,<span class="number">5</span>)</span><br><span class="line">r.decrby(<span class="string">'number'</span>,<span class="number">5</span>)</span><br><span class="line">r.incr(<span class="string">'number'</span>)</span><br><span class="line">r.decr(<span class="string">'number'</span>)</span><br><span class="line">r.incrbyfloat(<span class="string">'number'</span>,<span class="number">6.66</span>)</span><br><span class="line">r.incrbyfloat(<span class="string">'number'</span>,<span class="number">-6.66</span>)</span><br><span class="line"><span class="comment"># b'10'</span></span><br><span class="line">print(r.get(<span class="string">'number'</span>))</span><br></pre></td></tr></table></figure>
<p><strong>python操作list</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"></span><br><span class="line">r = redis.Redis(host=<span class="string">'192.168.43.49'</span>,port=<span class="number">6379</span>,db=<span class="number">0</span>)</span><br><span class="line"><span class="comment"># ['mysql','redis']</span></span><br><span class="line">r.lpush(<span class="string">'pylist'</span>,<span class="string">'redis'</span>,<span class="string">'mysql'</span>)</span><br><span class="line"><span class="comment"># ['mysql','redis','django','spider']</span></span><br><span class="line">r.rpush(<span class="string">'pylist'</span>,<span class="string">'django'</span>,<span class="string">'spider'</span>)</span><br><span class="line"><span class="comment"># ['mysql','redis','django','spider','AI']</span></span><br><span class="line">r.linsert(<span class="string">'pylist'</span>,<span class="string">'after'</span>,<span class="string">'spider'</span>,<span class="string">'AI'</span>)</span><br><span class="line"><span class="comment"># 5</span></span><br><span class="line">print(r.llen(<span class="string">'pylist'</span>))</span><br><span class="line"><span class="comment"># ['redis','django','spider']</span></span><br><span class="line">r.lpop(<span class="string">'pylist'</span>)</span><br><span class="line">r.rpop(<span class="string">'pylist'</span>)</span><br><span class="line"><span class="comment"># ['redis','django','spider']</span></span><br><span class="line">print(r.lrange(<span class="string">'pylist'</span>,<span class="number">0</span>,<span class="number">-1</span>))</span><br><span class="line"><span class="comment"># ['redis','spider']</span></span><br><span class="line">r.lrem(<span class="string">'pylist'</span>,<span class="number">0</span>,<span class="string">'django'</span>)</span><br><span class="line"><span class="comment"># 返回True，['redis']</span></span><br><span class="line">r.ltrim(<span class="string">'pylist'</span>,<span class="number">0</span>,<span class="number">0</span>)</span><br><span class="line"><span class="comment"># 返回True，['spiderman']</span></span><br><span class="line">r.lset(<span class="string">'pylist'</span>,<span class="number">0</span>,<span class="string">'spiderman'</span>)</span><br><span class="line"></span><br><span class="line">r.delete(<span class="string">'pylist'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>位图操作bitmap（重要）</strong></p>
<p>位图不是真正的数据类型，它是定义在字符串类型中<br>一个字符串类型的值最多能存储512M字节的内容，位上限：2^32</p>
<p><strong>强势点</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">可以实时的进行统计，极其节省空间。官方在模拟<span class="number">1</span>亿<span class="number">2</span>千<span class="number">8</span>百万用户的模拟环境下，在一台MacBookPro上，典型的统计如“日用户数”的时间消耗小于<span class="number">50</span>ms, 占用<span class="number">16</span>MB内存</span><br></pre></td></tr></table></figure>
<p><strong>设置某一位上的值</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">setbit key offset value</span><br><span class="line"><span class="comment"># offset是偏移量，从0开始</span></span><br></pre></td></tr></table></figure>
<p><strong>示例</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 默认扩展位以0填充</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; set mykey ab</span><br><span class="line">OK</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get mykey</span><br><span class="line"><span class="string">"ab"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SETBIT mykey <span class="number">0</span> <span class="number">1</span></span><br><span class="line">(integer) <span class="number">0</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; get mykey</span><br><span class="line"><span class="string">"\xe1b"</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<p><strong>获取某一位上的值</strong></p>
<p>GETBIT key offset</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; GETBIT mykey <span class="number">3</span></span><br><span class="line">(integer) <span class="number">0</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; GETBIT mykey <span class="number">0</span></span><br><span class="line">(integer) <span class="number">1</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<p><strong>bitcount</strong></p>
<p>统计键所对应的值中有多少个 1 </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SETBIT user001 <span class="number">1</span> <span class="number">1</span></span><br><span class="line">(integer) <span class="number">0</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; SETBIT user001 <span class="number">30</span> <span class="number">1</span></span><br><span class="line">(integer) <span class="number">0</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt; bitcount user001</span><br><span class="line">(integer) <span class="number">2</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">6379</span>&gt;</span><br></pre></td></tr></table></figure>
<p><strong>应用场景案例</strong></p>
<p>网站用户的上线次数统计（寻找活跃用户）</p>
<p>用户名为key，上线的天作为offset，上线设置为1</p>
<p>示例: 用户名为 user001 的用户，今年第1天上线，第30天上线</p>
<p>SETBIT user001 1 1 </p>
<p>SETBIT user001 30 1</p>
<p>BITCOUNT user001</p>
<p><strong>代码实现</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"></span><br><span class="line">r = redis.Redis(host=<span class="string">'192.168.43.49'</span>,port=<span class="number">6379</span>,db=<span class="number">2</span>,password=<span class="string">'123456'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># user1，一年之中第1天和第5天登录</span></span><br><span class="line">r.setbit(<span class="string">'user001'</span>,<span class="number">1</span>,<span class="number">1</span>)</span><br><span class="line">r.setbit(<span class="string">'user001'</span>,<span class="number">5</span>,<span class="number">1</span>)</span><br><span class="line"><span class="comment"># user2，一年之中第100天和第200天登录</span></span><br><span class="line">r.setbit(<span class="string">'user002'</span>,<span class="number">100</span>,<span class="number">1</span>)</span><br><span class="line">r.setbit(<span class="string">'user002'</span>,<span class="number">200</span>,<span class="number">1</span>)</span><br><span class="line"><span class="comment"># user3，一年之中好多天登录</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>,<span class="number">365</span>,<span class="number">2</span>):</span><br><span class="line">    r.setbit(<span class="string">'user003'</span>,i,<span class="number">1</span>)</span><br><span class="line"><span class="comment"># user4，一年之中好多天登录</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>,<span class="number">365</span>,<span class="number">3</span>):</span><br><span class="line">    r.setbit(<span class="string">'user004'</span>,i,<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">user_list = r.keys(<span class="string">'user*'</span>)</span><br><span class="line">print(user_list)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 活跃用户</span></span><br><span class="line">active_users = []</span><br><span class="line"><span class="comment"># 不活跃用户</span></span><br><span class="line">noactive_user = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> user <span class="keyword">in</span> user_list:</span><br><span class="line">    <span class="comment"># 统计位图中有多少个 1</span></span><br><span class="line">    login_count = r.bitcount(user)</span><br><span class="line">    <span class="keyword">if</span> login_count &gt;= <span class="number">100</span>:</span><br><span class="line">       active_users.append((user,login_count))</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      noactive_user.append((user,login_count))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 打印活跃用户</span></span><br><span class="line"><span class="keyword">for</span> active <span class="keyword">in</span> active_users:</span><br><span class="line">    print(<span class="string">'活跃用户:'</span>,active)</span><br></pre></td></tr></table></figure>
<p><strong>list案例: 一个进程负责生产url，一个进程负责消费url</strong></p>
<p>进程1: 生产者</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">urls_list = [</span><br><span class="line">    <span class="string">'01_baidu.com'</span>,</span><br><span class="line">    <span class="string">'02_sina.com'</span>,</span><br><span class="line">    <span class="string">'03_taobao.com'</span>,</span><br><span class="line">    <span class="string">'04_tmall.com'</span>,</span><br><span class="line">    <span class="string">'05_jd.com'</span></span><br><span class="line">]</span><br><span class="line">r = redis.Redis(host=<span class="string">'192.168.43.49'</span>,db=<span class="number">0</span>,password=<span class="string">'123456'</span>)</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    url = random.choice(urls_list)</span><br><span class="line">    r.lpush(<span class="string">'spider::urls'</span>,url)</span><br><span class="line">    time.sleep(random.randint(<span class="number">1</span>,<span class="number">5</span>))</span><br></pre></td></tr></table></figure>
<p>进程2: 消费者</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"></span><br><span class="line">r = redis.Redis(host=<span class="string">'192.168.43.49'</span>,db=<span class="number">0</span>,password=<span class="string">'123456'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    <span class="comment"># 结果为元组</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        url = r.blpop(<span class="string">'spider::urls'</span>,<span class="number">3</span>)</span><br><span class="line">        print(url[<span class="number">1</span>])</span><br><span class="line">        r.lrem(<span class="string">'spider::urls'</span>,count=<span class="number">0</span>,value=url[<span class="number">1</span>])</span><br><span class="line">    <span class="keyword">except</span>:</span><br><span class="line">        print(<span class="string">'爬取结束'</span>)</span><br><span class="line">        <span class="keyword">break</span></span><br></pre></td></tr></table></figure>
<p><img src="https://object.renchengqi.com/blog/o2xzb.png" alt></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Redis/" rel="tag"># Redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/02/redis/简述/" rel="next" title="Redis简述">
                <i class="fa fa-chevron-left"></i> Redis简述
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/29/datascience/数据分析-概述/" rel="prev" title="数据分析-概述">
                数据分析-概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#安装"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Ubuntu"><span class="nav-number">1.1.</span> <span class="nav-text">Ubuntu</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Windows"><span class="nav-number">1.2.</span> <span class="nav-text">Windows</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#配置文件详解"><span class="nav-number">2.</span> <span class="nav-text">配置文件详解</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#配置文件所在路径"><span class="nav-number">2.1.</span> <span class="nav-text">配置文件所在路径</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Ubuntu-1"><span class="nav-number">2.1.1.</span> <span class="nav-text">Ubuntu</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#windows"><span class="nav-number">2.1.2.</span> <span class="nav-text">windows</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置连接密码"><span class="nav-number">2.2.</span> <span class="nav-text">设置连接密码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#允许远程连接"><span class="nav-number">2.3.</span> <span class="nav-text">允许远程连接</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#远程连接测试"><span class="nav-number">2.4.</span> <span class="nav-text">远程连接测试</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Windows连接Ubuntu的Redis服务"><span class="nav-number">2.4.1.</span> <span class="nav-text">Windows连接Ubuntu的Redis服务**</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数据类型"><span class="nav-number">3.</span> <span class="nav-text">数据类型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#字符串类型-string"><span class="nav-number">3.1.</span> <span class="nav-text">字符串类型(string)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#特点"><span class="nav-number">3.1.1.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#必须掌握命令"><span class="nav-number">3.1.2.</span> <span class="nav-text">必须掌握命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#扩展命令"><span class="nav-number">3.1.3.</span> <span class="nav-text">扩展命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用命令"><span class="nav-number">3.1.4.</span> <span class="nav-text">常用命令</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#set-get命令"><span class="nav-number">3.1.4.1.</span> <span class="nav-text">set | get命令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#set命令之-setnx"><span class="nav-number">3.1.4.2.</span> <span class="nav-text">set命令之 - setnx</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#set命令之-ex"><span class="nav-number">3.1.4.3.</span> <span class="nav-text">set命令之 - ex</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#mset-mget"><span class="nav-number">3.1.4.4.</span> <span class="nav-text">mset | mget</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#strlen"><span class="nav-number">3.1.4.5.</span> <span class="nav-text">strlen</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串索引操作"><span class="nav-number">3.1.4.6.</span> <span class="nav-text">字符串索引操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#getrange-key-起始值-终止值"><span class="nav-number">3.1.4.7.</span> <span class="nav-text">getrange key 起始值 终止值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#append-key-value"><span class="nav-number">3.1.4.8.</span> <span class="nav-text">append key value</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#整数操作"><span class="nav-number">3.2.</span> <span class="nav-text">整数操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#应用场景"><span class="nav-number">3.2.1.</span> <span class="nav-text">应用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#浮点数操作"><span class="nav-number">3.3.</span> <span class="nav-text">浮点数操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#命令汇总"><span class="nav-number">3.4.</span> <span class="nav-text">命令汇总</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串操作"><span class="nav-number">3.4.1.</span> <span class="nav-text">字符串操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数字操作"><span class="nav-number">3.4.2.</span> <span class="nav-text">数字操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置过期时间的两种方式"><span class="nav-number">3.4.3.</span> <span class="nav-text">设置过期时间的两种方式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#方式一"><span class="nav-number">3.4.3.1.</span> <span class="nav-text">方式一</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#方式二"><span class="nav-number">3.4.3.2.</span> <span class="nav-text">方式二</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查看存活时间"><span class="nav-number">3.4.4.</span> <span class="nav-text">查看存活时间</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除过期"><span class="nav-number">3.4.5.</span> <span class="nav-text">删除过期</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通用命令"><span class="nav-number">3.5.</span> <span class="nav-text">通用命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#列表数据类型（List）"><span class="nav-number">3.5.1.</span> <span class="nav-text">列表数据类型（List）</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#特点-1"><span class="nav-number">3.5.1.1.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#头尾压入元素（LPUSH-RPUSH）"><span class="nav-number">3.5.1.2.</span> <span class="nav-text">头尾压入元素（LPUSH | RPUSH）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#查看-设置-列表元素"><span class="nav-number">3.5.1.3.</span> <span class="nav-text">查看|设置 列表元素</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#移除指定元素（LREM）"><span class="nav-number">3.5.1.4.</span> <span class="nav-text">移除指定元素（LREM）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#去除指定范围外元素（LTRIM）"><span class="nav-number">3.5.1.5.</span> <span class="nav-text">去除指定范围外元素（LTRIM）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#列表中插入值（LINSERT）"><span class="nav-number">3.5.1.6.</span> <span class="nav-text">列表中插入值（LINSERT）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#阻塞弹出（BLPOP-BRPOP）"><span class="nav-number">3.5.1.7.</span> <span class="nav-text">阻塞弹出（BLPOP | BRPOP）</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#与python交互"><span class="nav-number">4.</span> <span class="nav-text">与python交互</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
